"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Calendar, User, Tag, ArrowLeft } from "lucide-react";
import { API_ENDPOINTS, apiRequest } from "@/lib/api";
import { mockPosts } from "@/lib/mockData";
import { useQuery } from "@tanstack/react-query";

interface Post {
  id: string;
  title: string;
  slug: string;
  content: string;
  excerpt?: string;
  coverImage?: string;
  published: boolean;
  createdAt: string;
  updatedAt: string;
  author: {
    id: string;
    name: string;
  };
  tags: Array<{
    id: string;
    name: string;
  }>;
}

export default function PostDetailPage() {
  const params = useParams();
  const slug = params.slug as string;

  const {
    data: post,
    isLoading,
    isError,
    error,
  } = useQuery({
    queryKey: ["post", slug],
    queryFn: () => apiRequest<Post>(API_ENDPOINTS.POST_BY_SLUG(slug)),
    enabled: !!slug,
    retry: 1,
  });

  // 兼容 mock 数据逻辑
  const [useMockData, setUseMockData] = useState(false);
  const [mocked, setMocked] = useState<Post | null>(null);
  useEffect(() => {
    if (isError && slug) {
      const mockPost = mockPosts.find((p) => p.slug === slug);
      if (mockPost) {
        setUseMockData(true);
        setMocked(mockPost as Post);
      }
    }
  }, [isError, slug]);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (isError && !useMockData) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-500">
            获取文章详情失败:{" "}
            {error instanceof Error ? error.message : "未知错误"}
          </p>
        </div>
      </div>
    );
  }

  const renderPost = useMockData ? mocked : post;

  if (!renderPost) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-900 mb-4">文章未找到</h1>
          <p className="text-gray-600 mb-4">您访问的文章不存在或已被删除</p>
          <Link href="/posts">
            <Button>
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回文章列表
            </Button>
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 返回按钮 */}
        <div className="mb-6">
          <Link href="/posts">
            <Button variant="outline" size="sm">
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回文章列表
            </Button>
          </Link>
        </div>

        {/* 演示数据提示 */}
        {useMockData && (
          <div className="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
            <p className="text-sm text-yellow-800">
              📝 当前显示的是演示数据，后端 API 可能未启动
            </p>
          </div>
        )}

        {/* 文章内容 */}
        <Card className="mb-8">
          {renderPost.coverImage && (
            <div className="aspect-video overflow-hidden rounded-t-lg">
              <img
                src={renderPost.coverImage}
                alt={renderPost.title}
                className="w-full h-full object-cover"
              />
            </div>
          )}
          <CardHeader>
            <div className="flex items-center gap-2 mb-4 text-sm text-gray-500">
              <User className="h-4 w-4" />
              <span>{renderPost.author.name}</span>
              <Calendar className="h-4 w-4 ml-2" />
              <span>{formatDate(renderPost.createdAt)}</span>
            </div>
            <h1 className="text-3xl font-bold text-gray-900 mb-4">
              {renderPost.title}
            </h1>
            {renderPost.excerpt && (
              <p className="text-lg text-gray-600 mb-4">{renderPost.excerpt}</p>
            )}
            {renderPost.tags.length > 0 && (
              <div className="flex items-center gap-2">
                <Tag className="h-4 w-4 text-gray-400" />
                <div className="flex flex-wrap gap-2">
                  {renderPost.tags.map((tag) => (
                    <Badge key={tag.id} variant="secondary">
                      {tag.name}
                    </Badge>
                  ))}
                </div>
              </div>
            )}
          </CardHeader>
          <CardContent>
            <div className="prose prose-lg max-w-none">
              <div
                className="whitespace-pre-wrap text-gray-700 leading-relaxed"
                dangerouslySetInnerHTML={{
                  __html: renderPost.content
                    .replace(/\n/g, "<br>")
                    .replace(
                      /^# (.*$)/gim,
                      '<h1 class="text-2xl font-bold mb-4">$1</h1>'
                    )
                    .replace(
                      /^## (.*$)/gim,
                      '<h2 class="text-xl font-bold mb-3 mt-6">$1</h2>'
                    )
                    .replace(
                      /^### (.*$)/gim,
                      '<h3 class="text-lg font-bold mb-2 mt-4">$1</h3>'
                    )
                    .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
                    .replace(/\*(.*?)\*/g, "<em>$1</em>")
                    .replace(
                      /```(\w+)?\n([\s\S]*?)```/g,
                      '<pre class="bg-gray-100 p-4 rounded-md overflow-x-auto my-4"><code>$2</code></pre>'
                    )
                    .replace(
                      /`([^`]+)`/g,
                      '<code class="bg-gray-100 px-1 py-0.5 rounded text-sm">$1</code>'
                    )
                    .replace(/^- (.*$)/gim, '<li class="ml-4">$1</li>')
                    .replace(/^(\d+)\. (.*$)/gim, '<li class="ml-4">$2</li>'),
                }}
              />
            </div>
          </CardContent>
        </Card>

        {/* 文章信息 */}
        <Card>
          <CardContent className="pt-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
              <div>
                <span className="font-medium">作者：</span>
                <span>{renderPost.author.name}</span>
              </div>
              <div>
                <span className="font-medium">发布时间：</span>
                <span>{formatDate(renderPost.createdAt)}</span>
              </div>
              <div>
                <span className="font-medium">更新时间：</span>
                <span>{formatDate(renderPost.updatedAt)}</span>
              </div>
              <div>
                <span className="font-medium">状态：</span>
                <Badge variant={renderPost.published ? "default" : "secondary"}>
                  {renderPost.published ? "已发布" : "草稿"}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
